package com.candy.localaccount;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SyncAdapterType;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.View;

public class MainActivity extends Activity {

    private static final String TAG = "MainActivity";

    private AccountManager accountManager;
    private Context mContext;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mContext = getApplicationContext();
        accountManager = AccountManager.get(mContext);
    }

    public void btnClick1(View v) {
//        createPhoneAccountIfNotExist();
        if(PermissionsUtil.hasContactsPermissions(mContext)) {
            createCandyLocalAccountIfNotExist();
        } else {
            Utils.getAppDetailSettingIntent(mContext);
        }
    }

    public void btnClick2(View v) {
        deleteAccount(Utils.ACCOUNT_NAME_CANDY, Utils.ACCOUNT_TYPE_CANDY);
    }

    public void btnClick3(View v) {
//        getSyncAccounts();
        getAllAccounts();
    }

    void getAllAccounts(){
        Account[] accounts = accountManager.getAccounts();
        String[] items = new String[accounts.length];
        for (int i=0;i<accounts.length;i++) {
            items[i] = accounts[i].name + " (" + accounts[i].type + ")";
        }

        new AlertDialog.Builder(this)
                .setItems(items, null)
                .setNegativeButton(android.R.string.cancel,null)
                .create().show();
    }

    public void getSyncAccounts() {
        SyncAdapterType[] syncAdapterTypes = ContentResolver.getSyncAdapterTypes();
        String[] items = new String[syncAdapterTypes.length];
        for (int i=0;i<syncAdapterTypes.length;i++) {
            items[i] = syncAdapterTypes[i].accountType + " - authority:" + syncAdapterTypes[i].authority + " -Visible:"
            + syncAdapterTypes[i].isUserVisible();
        }

        new AlertDialog.Builder(this)
                .setItems(items, null)
                .setNegativeButton(android.R.string.cancel,null)
                .create().show();
    }

    private void createPhoneAccountIfNotExist() {
        if (findAccount(Utils.ACCOUNT_NAME_PHONE,
                Utils.ACCOUNT_TYPE_PHONE) != null) {
            Log.d(TAG, "phone account already exist");
            return;
        }
        mContext.startService(new Intent(mContext, PhoneAuthenticateService.class));
        updateAccountVisible(Utils.ACCOUNT_NAME_PHONE,
                Utils.ACCOUNT_TYPE_PHONE);
    }

    private void createCandyLocalAccountIfNotExist() {
        if (findAccount(Utils.ACCOUNT_NAME_CANDY,
                Utils.ACCOUNT_TYPE_CANDY) != null) {
            Log.d(TAG, "candy account already exist");
            return;
        }
        mContext.startService(new Intent(mContext, CandyAuthenticateService.class));
        updateAccountVisible(Utils.ACCOUNT_NAME_CANDY,
                Utils.ACCOUNT_TYPE_CANDY);
    }

    private Account findAccount(String accountName, String accountType) {
        for (Account account : accountManager.getAccountsByType(accountType)) {
            if (account.name.equals(accountName)) {
                return account;
            }
        }
        return null;
    }

    private void updateAccountVisible(String accountName, String accountType) {
        /*if (!hasContactsProviderExist()) {
            Log.d(TAG, "contacts content provider not exist");
            return;
        }*/

        final ContentResolver resolver = mContext.getContentResolver();
        Log.d(TAG, "updateAccountVisible account is " + accountName);
        // only do this when create
        final ContentValues values = new ContentValues();
        values.put(ContactsContract.Settings.ACCOUNT_NAME, accountName);
        values.put(ContactsContract.Settings.ACCOUNT_TYPE, accountType);
        values.put(ContactsContract.Settings.SHOULD_SYNC, 1);
        values.put(ContactsContract.Settings.UNGROUPED_VISIBLE, 1);
        resolver.insert(ContactsContract.Settings.CONTENT_URI, values);
    }

    /*private boolean hasContactsProviderExist() {
        IContentProvider provider = null;
        try {
            provider = getContentResolver().acquireProvider(ContactsContract.AUTHORITY);
        } finally {
            if (provider != null) {
                getContentResolver().releaseProvider(provider);
            }
        }
        return provider != null;
    }*/

    //delete
    private void deleteAccount(String accountName, String accountType) {
        if (findAccount(accountName, accountType) != null) {
            accountManager.removeAccount(
                    new Account(accountName, accountType), null, null);
            Log.d(TAG, "deleteAccount...");
        }
    }
}
